//
// Created by xsh on 2025/5/30.
//

#include <math.h>
#include <cstring>
#include <string>
#include "../../../../app/src/main/jni/include/instrument.h"
#include "SinSynth.h"
//SinSynth::SinSynth() {}
//SinSynth::~SinSynth(){};

// 创建乐器实例
SinSynth* createInstrument()
{
   //return new SinSynth();
}
// 销毁乐器实例
void destroyInstrument(Instrument *inst)
{
    delete static_cast<SinSynth *>(inst); // 转换为实际类型后删除
}
SinSynth::SinSynth() {}
SinSynth::~SinSynth() {}
double SinSynth::genWave(short* buffer, int numSamples,double phase, double sampleRate)
{
    const double phaseIncrement = 2.0 * M_PI * frequency / sampleRate;

    for (int i = 0; i < numSamples; ++i) {
        double sample = amp * sin(phase);
        buffer[i] = static_cast<short>(sample * amp * 32767);
        phase += phaseIncrement;
    }

    return fmod(phase, 2.0 * M_PI); // 返回更新后的相位
}
void SinSynth::onEvent(const char* eventName, jobject value, JNIEnv* env)
{
    if (strcmp(eventName, "setFrequency") == 0) {
        // 从Java对象获取值
        jclass doubleClass = env->FindClass("java/lang/Double");
        jmethodID doubleValue = env->GetMethodID(doubleClass, "doubleValue", "()D");
        frequency = env->CallDoubleMethod(value, doubleValue);*/
    }
    else if (strcmp(eventName, "setAmplitude") == 0)
    {
        jclass doubleClass = env->FindClass("java/lang/Double");
        jmethodID doubleValue = env->GetMethodID(doubleClass, "doubleValue", "()D");
        jdouble jAmp = env->CallDoubleMethod(value, doubleValue);
        this->amp = static_cast<double>(jAmp); // 将 jdouble 转为 double
    }
}